package top.cardone.data.action;

import com.google.common.base.Charsets;
import com.google.common.collect.Lists;
import com.google.common.reflect.TypeToken;
import com.google.gson.Gson;
import lombok.Setter;
import lombok.extern.log4j.Log4j2;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.ArrayUtils;
import org.springframework.core.io.Resource;
import top.cardone.context.ApplicationContextHolder;
import top.cardone.core.util.action.Action0;
import top.cardone.data.service.CrudService;

import java.io.IOException;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by yao hai tao on 2016/4/18.
 */
@Log4j2
public class InitDataAction implements Action0 {
	@Setter
	private Resource[] jsonFiles;

	@Setter
	private String serviceBeanId;

	@Setter
	private boolean reinit = false;

	@Override
	public void action() {
		if (ArrayUtils.isEmpty(jsonFiles)) {
			return;
		}

		for (Resource jsonFile : jsonFiles) {
			if (!jsonFile.exists()) {
				continue;
			}

			try {
				String json = FileUtils.readFileToString(jsonFile.getFile(), Charsets.UTF_8);

				List<Map<String, Object>> saveMapList = ApplicationContextHolder.getBean(Gson.class).fromJson(json, new TypeToken<List<LinkedHashMap<String, Object>>>() {
				}.getType());

				if(reinit){
					ApplicationContextHolder.func(CrudService.class, service -> service.saveList(Lists.newArrayList(saveMapList)), serviceBeanId);
				}else{
					ApplicationContextHolder.func(CrudService.class, service -> service.insertListByNotExists(Lists.newArrayList(saveMapList)), serviceBeanId);
				}
			} catch (IOException e) {
				log.error(e.getMessage(), e);
			}
		}
	}
}
